package br.com.ac.fatureweb.utilitary.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.ac.fatureweb.utilitary.FacesUtils;

@FacesConverter("cpfConverter")
public class CPFConverter implements Converter
{

	/*
	 * (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
	 */
	@Override
	public Object getAsObject(final FacesContext ctx, final UIComponent comp,
			final String value)
	{
		if ( value != null )
		{
			if ( value.length() == 14 && value.contains(".") && value.contains("-") )
			{
				String s = value.replace(".", "");
				s = s.replaceAll("-", "");
				return s;
			}
			FacesUtils.addMessageError("O CPF deve estar no formato 000.000.000-00");
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public String getAsString(final FacesContext ctx, final UIComponent comp,
			final Object value)
	{
		if ( value != null )
		{
			final String s = value.toString().trim();
			if ( s.toString().length() == 11 )
			{
				final String tmp = s.toString();

				final StringBuilder sb = new StringBuilder();

				sb.append(tmp.substring(0, 3));
				sb.append('.');
				sb.append(tmp.substring(3, 6));
				sb.append('.');
				sb.append(tmp.substring(6, 9));
				sb.append('-');
				sb.append(tmp.substring(9, 11));

				return sb.toString();
			}
		}

		return "";
	}
}
